package com.kay.service.impl;

import com.kay.mapper.AuthCodeMapper;
import com.kay.pojo.AuthCode;
import com.kay.service.CodeService;
import com.kay.service.EmailService;
import com.kay.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description:
 * @Author: Kay
 * @CreateDate: 2021/9/17$ 21:34$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/9/17$ 21:34$
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Reference
    private EmailService emailService;

    @Reference
    private UserService userService;

    @Autowired
    private AuthCodeMapper authCodeMapper;

    /**
     * 成验证码并发送到对应邮箱
     * 1.验证码为随机⽣成的6位数字 验证码存储到mysql数据库中
     * 2.验证码存储到mysql数据库之后，使⽤发邮件功能，将该验证码发送到所输⼊的邮箱地址中
     *
     * @param email
     * @return
     */
    @Override
    public boolean createCodeAndSendEmail(String email) {
        // 判断邮箱是否注册过
        boolean registered = userService.isRegistered(email);
        if (registered) return false;

        // 生成验证码 （随机⽣成的6位数字）
        String randomNumberS = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        System.out.println("code =========>>>>>>> " + randomNumberS);

        LocalDateTime currentTime = LocalDateTime.now();
        // 10分钟内有效
        LocalDateTime expireTime = currentTime.plusMinutes(10);
        //  验证码存放到数据库中
        AuthCode authCode = new AuthCode(email, randomNumberS, currentTime, expireTime);
        authCodeMapper.insert(authCode);

        // 验证码发送到对应邮箱
        emailService.sendMail(email, randomNumberS);
        return true;
    }

    /**
     * 校验邮箱对应的验证码是否有效
     *
     * @param email
     * @param code
     * @return 0正确 1错误 2超时
     */
    @Override
    public Integer validateCodeAndEmail(String email, String code) {
        Example example = new Example(AuthCode.class);
        example.createCriteria()
                .andEqualTo("email", email)
                .andEqualTo("code", code);
        example.orderBy("createTime").desc();
        List<AuthCode> authCodes = authCodeMapper.selectByExample(example);
        if (authCodes == null || authCodes.size() <= 0) return 1;

        AuthCode authCode = authCodes.get(0);
        if (LocalDateTime.now().compareTo(authCode.getExpireTime()) > 0) return 2;

        return 0;
    }
}
